(function ($) {
	var mustPull,optionPull;
	var mustStart = 0, optionStart = 0,Limit = 20;
	var mustPulling = false,optionPulling = false;
	var mustData=[],optionData=[];
	var loginID = '',TomcatUrl = ''
	$.init();
	$.plusReady(function () {
	    baseSetup();
	})
	if (!mui.os.plus) {
		baseSetup()
	}
	//待培训
	function getMustData(){
		if (mustPulling) {
			mustPull.endPullUpToRefresh()
			return;
		}
		mustPulling = true
		// parr 开始日期^结束日期^查询条件类型(1:主题，2：类型，3：级别，4：状态)^Y必修 N选修^O:预约，S:"学员培训"，T:"讲师培训"
		var parr = '^^1^Y^S'; //Y必修 N选修 1是主题
		var pdict = {'parr':parr,'input':$('#search')[0].value,'loginID':loginID,'start':mustStart,'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			mustPulling = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				mustPull.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (mustStart == 0) {
				mustData = dataArr
				$('#mustUL')[0].innerHTML = ''
			}else{
				mustData = mustData.concat(dataArr)
			}
			updateMustUI(dataArr,'mustUL')
			if (dataArr.length < Limit) {
				mustPull.endPullUpToRefresh(true);
			}else{
				mustPull.endPullUpToRefresh();
			}
			mustStart += dataArr.length;
		}, function(errorStr) {
			mustPull.endPullUpToRefresh();
			mustPulling = false
		});
	}
	function updateMustUI(dataArr,ulId){
		var mustUL = $('#'+ulId)[0]
		var index = 0
		if (ulId != 'mustUL') {
			index = 1
		}
		var oldcount = mustUL.querySelectorAll('li').length
		for(var i=0; i < dataArr.length; i++){
			var dict = dataArr[i]
			var wayDesc = dict['ReleaseWay'] == 'O'?'上':'下' 
			var levelDesc = ''//H:院级,L:科级,W:病区
			var level = dict['ReleaseLevel']
			if (level == 'H') {
				levelDesc = '院级'
			}else if (level == 'L') {
				levelDesc = '科级'
			}else if (level == 'W') {
				levelDesc = '病区'
			}
			var html = '<div class="classTitle">'+dict['ReleaseDesc']+'</div>'+
				//级别 类型 方式 讲师 学分
				'<div class="classInfo"><div>'+levelDesc+'</div><div>'+(dict['ReleaseDrillTypeDesc']||' ')+'</div><div>线'+wayDesc+'培训</div>'+
				'<div>'+(index == 0?'必修':'选修')+'</div><div>'+dict['DrillCredit']+'分</div></div>'+
				'<div class="classSubInfo">培训日期：'+dict['StartDate']+' - '+dict['EndDate']+'</div>'
			if(wayDesc == '下'){
				//TimeList: "2023-07-19 00:00」2023-08-19 00:00」2023-07-31 00:00」考核地点」5「2023-08-19 00:00」2023-09-19 00:00」2023-08-31 00:00」考核地点2」2「2023-09-19 00:00」2023-10-19 00:00」2023-09-30 00:00」考核地点3」3"
				var TimeList = dict['TimeList'].split('「')
				var timeArr = TimeList[parseInt(dict['OrderNum'])-1].split('」')
				html += '<div class="classSubInfo">课程时间：'+timeArr[0]+' - '+timeArr[1]+'</div>'+
				'<div class="classSubInfo">培训地点：'+timeArr[3]+'</div>'
			}
			if (dict['startStatus'] == 'N') {
				html +='<div class="process noStart">未开始</div>'
			}else if (dict['startStatus'] == 'E') {
				html +='<div class="process noStart">已结束</div>'
			}else if (dict['DrillResult']!="Y") { //startStatus N未开始 Y已开始 E已结束
				html +='<div class="process">完成'+(dict['DrillStep']==""?'0':dict['DrillStep'])+'/5</div>'+
					'<div class="mui-btn mui-btn-primary baseBtn">去培训</div>'
			}else{
				html += '<div class="resultArea"><div class="resultText">'+dict['DrillResultDesc']+'</div> 获得学分:'+dict['UseDrillScore']+'</div>'
				if(wayDesc == '上'){ //线上课程才可以再次学习,且只能看课件.
					html += '<div class="baseBtn trainAgain">再次学习</div>'
				}
				html +='<div class="baseBtn resultBtn">查看结果</div>'
			}
			var newLi = document.createElement('li')
			mustUL.appendChild(newLi)
			newLi.setAttribute('class','mui-table-view-cell')
			newLi.innerHTML = html
			newLi.id = index +'-' + (oldcount + i)
			var toTrainBtn = newLi.querySelector('.mui-btn-primary')
			if (toTrainBtn) {
				toTrainBtn.addEventListener('tap',toTrainTapped)
			}
			var trainAgain = newLi.querySelector('.trainAgain')
			if (trainAgain) {
				trainAgain.addEventListener('tap',trainAgainBtnTapped)
			}
			var resultBtn = newLi.querySelector('.resultBtn')
			if (resultBtn) {
				resultBtn.addEventListener('tap',resultBtnTapped)
			}
		}
	}

	function getOptionData(){
		if (optionPulling) {
			optionPull.endPullUpToRefresh()
			return;
		}
		optionPulling = true
		var parr = '^^1^N^S'; //Y必修 N选修 1是主题
		var pdict = {'parr':parr,'input':$('#search')[0].value,'loginID':loginID,'start':optionStart,'limit':Limit}
		//console.log(JSON.stringify(pdict))
		var paramDict = {'method':'web.INMTeaComm:FindDrillReleaseList','params':JSON.stringify(pdict),'type':'RecQuery'}
		$.DHCWebService(paramDict, function(result) {
			//console.log(JSON.stringify(result))
			optionPulling = false
			if (result['msgcode'] != '1') {
				mui.toast(result.msg)
				optionPull.endPullUpToRefresh();
				return
			}
			var dataArr = result.data
			if (optionStart == 0) {
				optionData = dataArr
				$('#optionUL')[0].innerHTML = ''
			}else{
				optionData = optionData.concat(dataArr)
			}
			updateMustUI(dataArr,'optionUL')
			if (dataArr.length < Limit) {
				optionPull.endPullUpToRefresh(true);
			}else{
				optionPull.endPullUpToRefresh();
			}
			optionStart += dataArr.length;
		}, function(errorStr) {
			optionPull.endPullUpToRefresh();
			optionPulling = false
		});
	}

	function toTrainTapped(){
		var liArr = this.parentNode.id.split('-')
		var index = parseInt(liArr[1])
		var dict
		if (parseInt(liArr[0]) == 0) {
			dict = mustData[index]
		}else{
			dict = optionData[index]
		}
		var webview = plus.webview.create('toTrain.html', 'toTrain', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict});
		webview.show('fade-in');
		webview.addEventListener('close',function(){
			refreshMainPage(parseInt(liArr[0]))
		})
	}
	function resultBtnTapped(){
		var liArr = this.parentNode.id.split('-')
		var index = parseInt(liArr[1])
		var dict
		if (parseInt(liArr[0]) == 0) {
			dict = mustData[index]
		}else{
			dict = optionData[index]
		}
		var webview = plus.webview.create('trainResult.html', 'trainResult', {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict,pageType:'look'});
		webview.show('fade-in');
		webview.addEventListener('close',function(){
			refreshMainPage(parseInt(liArr[0]))
		})
	}
	// 线上课程才可以再次学习,且只能看课件.
	function trainAgainBtnTapped(){
		var liArr = this.parentNode.id.split('-')
		var index = parseInt(liArr[1])
		var dict
		if (parseInt(liArr[0]) == 0) {
			dict = mustData[index]
		}else{
			dict = optionData[index]
		}
		var page = 'trainVideo'
		var filesUrl = dict['filesUrl']
		var tempArr = filesUrl.split('.')
		var fileType = tempArr[tempArr.length -1]
		var url = ''
		if (fileType == 'pdf') {
			page = '../FilePreview/pdfReader'
			url = TomcatUrl+'/'+encodeURI(dict['filesUrl'])
		}
		var webview = plus.webview.create(page+'.html', page, {
			background: '#fff',
			statusbar: {
				background: '#fff'
			}
		},{sourceData:dict,pageType:'look','title':dict['fileName'],'fileUrl':url});
		webview.show('fade-in');
		webview.addEventListener('close',function(){
			refreshMainPage(parseInt(liArr[0]))
		})
	}
	
	function baseSetup(){
		$('.mui-scroll-wrapper').scroll({
			bounce: true,
			indicators: false, //是否显示滚动条
		});
		var perInfo = app.getState()
		loginID = perInfo['loginID']
		TomcatUrl = perInfo.TomcatUrl
		mui("body").on("tap", ".searchArea .mui-icon-clear", function() {
			if (document.getElementById('search').value != "") {
				document.getElementById('search').value = ""
			}
			refreshMainPage()
		});
		var slider = document.getElementById('slider');
		slider.addEventListener('slide', function(event) {
			var index = event.detail.slideNumber;
			refreshMainPage(index)
			$('#sliderIndicator .mui-indicator[data-index="'+index+'"]')[0].classList.add('mui-active');
		});
		var indicators = document.querySelectorAll('#sliderIndicator .mui-indicator');
		for (var i = 0; i < indicators.length;i++) {
			indicators[i].addEventListener('tap',function(){
				var oldActive = $('#sliderIndicator .mui-indicator.mui-active')[0];
				if (oldActive) {
					if (oldActive == this) {
						return
					}
					oldActive.classList.remove('mui-active')
				}
				var newIndex = parseInt(this.getAttribute('data-index'))
				refreshMainPage(newIndex)
				this.classList.add('mui-active')
				mui('#slider').slider().gotoItem(newIndex,100)
			});
		}
		var search = document.getElementById('search');
		search.addEventListener('input',function(){
			refreshMainPage()
		});
		//待培训
		var mustScroll = document.getElementById('mustScroll');
		mustPull = $(mustScroll).pullToRefresh({
			up: {
				callback: function() {
					getMustData()
				}
			}
		});
		//待培训
		var optionScroll = document.getElementById('optionScroll');
		optionPull = $(optionScroll).pullToRefresh({
			up: {
				callback: function() {
					getOptionData()
				}
			}
		});
		
		getMustData();
		getOptionData();
	}
	function refreshMainPage(newIndex){
		if (newIndex == undefined) {
			resetMustRefresh();
			resetOptionRefresh()
			return
		}
		if (newIndex == 0){
			resetMustRefresh();
		}else if(newIndex == 1){
			resetOptionRefresh()
		}
	}
	function resetMustRefresh(){
		mustStart = 0;
		mustData = []
		$('#mustUL')[0].innerHTML = '';
		$('#mustWrapper').scroll().scrollTo(0,0,100);
		if (mustPull) {
			mustPull.refresh(true)
		}
		getMustData();
	}
	function resetOptionRefresh(){
		optionStart = 0;
		optionData = []
		$('#optionUL')[0].innerHTML = '';
		$('#optionWrapper').scroll().scrollTo(0,0,100);
		if (optionPull) {
			optionPull.refresh(true)
		}
		getOptionData();
	}
})(mui);